#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash 3dslicer-5.0.3.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
set -e
yum install -y wget tar environment-modules libatomic

if `wget -t 40 -c -P $buildpath  https://ghproxy.com/https://github.com/Slicer/Slicer/archive/refs/tags/v5.0.3.tar.gz`
then 
   echo "v5.0.3.tar.gz下载成功!(国内github加速下载)"
elif `wget -t 40 -c -P $buildpath  https://github.com/Slicer/Slicer/archive/refs/tags/v5.0.3.tar.gz`
then 
   echo "v5.0.3.tar.gz下载成功!"
else
   echo "v5.0.3.tar.gz下载失败!"
fi

tar xf $buildpath/v5.0.3.tar.gz -C $buildpath && rm -rf $buildpath/v5.0.3.tar.gz
src_path=$(cd $(dirname "${BASH_SOURCE[0]}") >/dev/null && pwd)
cp $src_path/dependency/src/* $buildpath/Slicer-5.0.3
mv -f $buildpath/Slicer-5.0.3/External_*.cmake $buildpath/Slicer-5.0.3/SuperBuild
mkdir -p $buildpath/Slicer-5.0.3/build/ExternalData/Objects
tar xf $buildpath/Slicer-5.0.3/Hash.tar.gz -C $buildpath/Slicer-5.0.3/build/ExternalData/Objects
cd $buildpath/Slicer-5.0.3
sed -i "s/-m pip install /&-i https:\/\/pypi.tuna.tsinghua.edu.cn\/simple /g" `grep -rl "\-m pip install" SuperBuild`
mkdir -p $installpath/3dslicer-5.0.3
cp -r $buildpath/Slicer-5.0.3/* $installpath/3dslicer-5.0.3
    
cat >$installpath/3dslicer-5.0.3/3dslicer_modulefiles<<EOF
#%Module1.0
conflict 3dslicer
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set SLICER \$pwd
setenv SLICER \$SLICER
prepend-path PATH \$SLICER/build/Slicer-build
EOF

rm -rf $buildpath/Slicer-5.0.3


